# matching system for 2 programs
require_relative 'lib'
require_relative 'macrofunc'
require_relative 'scheduler'

p0 = 'ruby cdemon.rb 0'
p1 = 'ruby demon.rb 1'

pipe0 = IO.popen(p0, "w+")
pipe1 = IO.popen(p1, "w+")

$p0_score = 0
$p1_score = 0

def check_win
  $p0_score = 0
  $p1_score = 0
  $my_slots.each {|s| $p0_score+=1 if s.vitality > 0}
  $enemy_slots.each {|s| $p1_score+=1 if s.vitality > 0}

  if($p0_score == 0 || $p1_score == 0 || $step > 100000)
    puts "Ended in #{$step} steps with score #{$p0_score}:#{$p1_score}"
    puts $p0_score > $p1_score ? "Player 0 wins!" : $p0_score == $p1_score ? "Tie" : "Player 1 wins!"
    exit
  end
end

$step = 0
while true

  #player 0 step
  lr = pipe0.gets.chomp.to_i
  pipe1.puts lr
  case lr
    when 1
      card = pipe0.gets.chomp
      slot = pipe0.gets.to_i

      pipe1.puts card
      pipe1.puts slot
    when 2
      slot = pipe0.gets.to_i
      card = pipe0.gets.chomp

      pipe1.puts slot
      pipe1.puts card
  end

  do_application(lr, slot, card)
  check_win
  swap_slots

  #player 1 step
  lr = pipe1.gets.chomp.to_i
  pipe0.puts lr
  case lr
    when 1
      card = pipe1.gets.chomp
      slot = pipe1.gets.to_i

      pipe0.puts card
      pipe0.puts slot
    when 2
      slot = pipe1.gets.to_i
      card = pipe1.gets.chomp

      pipe0.puts slot
      pipe0.puts card
  end

  do_application(lr, slot, card)
  swap_slots
  check_win

  $step+=1
  if(($step % 1000) == 0)
    puts "step=#{$step} score #{$p0_score}:#{$p1_score}"
  end
  break if $step > 100000
end
check_win
